package com.fast.fastenjoy.base.dao.jdbc;

import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.util.Assert;

@SuppressWarnings("deprecation")
public class JdbcTemplate {

	protected SimpleJdbcTemplate jdbcTemplate;
	protected SimpleJdbcInsert simpleJdbcInsert;
	
	public JdbcTemplate(DataSource dataSource){
		jdbcTemplate = new SimpleJdbcTemplate(dataSource);
		simpleJdbcInsert = new SimpleJdbcInsert(dataSource);
	}
	
	/**
	 * 根据sql语句，返回对象集合
	 * @param sql语句(参数用冒号加参数名，例如select * from tb where id=:id)
	 * @param clazz类型
	 * @param parameters参数集合(key为参数名，value为参数值)
	 * @return bean对象集合
	 */
	public List<?> find(final String sql, Class<?> clazz, Map<String, Object> parameters){
		
		try{
			
			Assert.hasText(sql, "sql语句不正确!");
			Assert.notNull(clazz, "集合中对象类型不能为空!");
			
			if(parameters != null){
				return jdbcTemplate.query(sql, resultBeanMapper(clazz), parameters);
			}else{
				return jdbcTemplate.query(sql, resultBeanMapper(clazz));
			}
			
		}catch (Exception e) {
			return null;
		}
	}
	
	protected ParameterizedBeanPropertyRowMapper<?> resultBeanMapper(Class<?> clazz) {
		return ParameterizedBeanPropertyRowMapper.newInstance(clazz);
	}
	
	protected BeanPropertySqlParameterSource paramBeanMapper(Object object) {
		return new BeanPropertySqlParameterSource(object);
	}
	
}
